package cn.edu.hitsz.conf;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.InvalidKeyException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
 * Read initial parameters from configuration file
 * 
 * @author mingchen
 * 
 */
public class LoadConfiguration {

	private final static Properties pps = new Properties();

	/**
	 * load the configuration file
	 * 
	 * @param fileName
	 *            the config file name void 2015年8月7日上午10:16:21
	 */
	public static void init(String fileName){
		try{
			InputStreamReader isr = new InputStreamReader(new FileInputStream(fileName));
			pps.load(isr);
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	/**
	 * initialize the configuration file and load the file content
	 */
	static{
		init("conf.ini");
	}

	/**
	 * Get value from the pps by given a key
	 * 
	 * @param key
	 * @return String 2015年8月7日上午10:25:07
	 */
	public static String getStringValueByKey(Object key) {
		String value = "";
		if (pps.containsKey(key)){
			value = pps.getProperty((String)key);
		}else{
			try {
				throw new InvalidKeyException("Key "+key+" is not found in config");
			} catch (InvalidKeyException e) {
				e.printStackTrace();
			}
		}
		return value;
	}

	/**
	 * Get int value from the key
	 * 
	 * @param key
	 * @return int
	 * 
	 *         2015年8月7日
	 */
	public static int getIntValueByKey(String key) {
		String value = "";
		if (pps.containsKey(key)) {
			value = pps.getProperty(key);
		} else {
			try {
				throw new InvalidKeyException("Key " + key
						+ " is not found in config");
			} catch (InvalidKeyException e) {
				e.printStackTrace();
			}
		}
		return Integer.parseInt(value);
	}

	/**
	 * Get all the key:value pair from pps and store in hashmap
	 * 
	 * @return Map<String,String> 2015年8月7日上午10:36:32
	 */
	public static Map<String,String> getAllKeyAndValues(){
		Map<String,String> map = new HashMap<String,String>();
		for(Object obj:pps.keySet()){
			map.put((String) obj, getStringValueByKey(obj));
		}
		return map;
	}
}
